<?php

namespace app\http\middleware;


use app\common\model\Permission;
use app\common\model\RolePermission;
use think\Exception;
use think\facade\Request;
use think\facade\Session;

class PermissionCheck
{
    public $_notNeedCheck = [
        'Index','Login','Upload'
    ];
    public function handle($request, \Closure $next)
    {

        /*
         * 因为redis公用了同一套，所以直接判断session信息
         *
         * */
        //获取session的登陆信息 判断是否有
        //根据当前的用户角色获取权限菜单

        $locaController = Request::controller();
        if(!in_array($locaController,$this->_notNeedCheck)){
            if(Session::get('is_super') != 1){
                //查询当前的权限
                $rolePermission = RolePermission::where(['role_id'=>Session::get('roles_id')])
                    ->select()->toArray();
                if(!$rolePermission){
                    if(Request::isAjax()){
                        wapAjaxReturn(10040,'您暂时没有权限操作');
                    }
                    //跳转登陆
                    throw new Exception('您暂时没有权限操作');
                }else{
                    $perList = array_column($rolePermission,'permission_action');
                    if(!in_array($locaController,$perList)){
                        if(Request::isAjax()){
                            wapAjaxReturn(10040,'您暂时没有权限操作');
                        }
                        //跳转登陆
                        throw new Exception('您暂时没有权限操作');
                    }
                }
            }
        }

        return $next($request);

    }

}
